package com.neo.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.neo.entity.errorMessage.RespErrorCode;
import com.neo.util.ErrorFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.neo.util.DateUtil;
import com.neo.util.DjsStringUtil;

@Service
public class DjsProjectFileService {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    public String generalFile(String batch) throws Exception {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT * FROM jx_invest_project " + 
        		"", new Object[]{});

        List<String> resList = new ArrayList<>();
        for (Map map : list) {
            String project_no = (String) map.get("PROJECT_NO");
            String project_name = (String) map.get("PROJECT_NAME");
            String borrower_account_id = (String) map.get("BORROWER_ACCOUNT_ID");
            BigDecimal loan_amt = (BigDecimal) map.get("LOAN_AMT");
            String interest_pay_type = (String) map.get("INTEREST_PAY_TYPE");
            String interest_pay_day = (String) map.get("INTEREST_PAY_DAY");
            if ("1".equals(interest_pay_type)) {
            	interest_pay_day = cutinterestPayDay(interest_pay_day);
            }else {
            	interest_pay_day =null;
            }
            Integer loan_ment = (Integer) map.get("LOAN_MENT");
            BigDecimal invest_rate = (BigDecimal) map.get("INVEST_RATE");
            String bail_account_id = (String) map.get("BAIL_ACCOUNT_ID");
            String nominal_account_id = (String) map.get("NOMINAL_ACCOUNT_ID");
            Date make_loan_time = (Date) map.get("MAKE_LOAN_TIME");

            //int loan_ment_day = getLoanMent(loan_ment, make_loan_time);
            if (loan_ment == null)
                continue;
            if (loan_amt == null)
                continue;
            if (invest_rate == null)
                continue;
            loan_amt = loan_amt.setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal("100")).setScale(0, BigDecimal.ROUND_DOWN);//去2位小数再变整数
            invest_rate = invest_rate.multiply(new BigDecimal("100000")).setScale(0, BigDecimal.ROUND_DOWN);
            String res = DjsStringUtil.BANKID
                    + batch
                    + DjsStringUtil.fillBlank(project_no, 40) //标的编号
                    + DjsStringUtil.fillBlank(project_name, 60) //标的描述
                    + DjsStringUtil.fillBlank(borrower_account_id, 19) //借款人电子账号
                    + DjsStringUtil.fillLeftZero(loan_amt.toString(), 13) //借款金额
                    + DjsStringUtil.fillBlank("2", 1)        //付息方式
                    + DjsStringUtil.fillBlank("", 2)        //利息每月支付日
                        + DjsStringUtil.fillLeftZero(loan_ment.toString(), 4)        //项目期限
                    + DjsStringUtil.fillLeftZero(invest_rate.toString(), 8)//预期年化收益率
                    + DjsStringUtil.fillBlank(bail_account_id, 19) //担保人电子账号
                    + DjsStringUtil.fillBlank(nominal_account_id, 19) //名义借款人电子账号
                    + "0" //多种借款人模式标志
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 19) //收款人电子账户
                    + "0" //受托支付标志
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 100) //保留域
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 100) //第三方平台保留域
                    ;
            System.out.println(res);

            byte[] bs = res.getBytes("GBK");
            if (bs.length != 416) {
                System.out.println("长度错误");
            }
            ;
            resList.add(res);
        }
        System.out.println("生成文件行数" + resList.size());


        SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String strDate = dateFormater.format(date);
        String fileName = DjsStringUtil.FILE_PATH + DjsStringUtil.BANKID + "-BIDIN-" + DjsStringUtil.COINSTCODE + "-" + batch + "-" + strDate;
        DjsStringUtil.writeStringToFile(resList, batch, fileName);

        System.out.println("生成文件:" + fileName);
        return fileName;
    }

    private String cutinterestPayDay(String interest_pay_day) {
		if (interest_pay_day!=null && interest_pay_day.length()>2) {
			return interest_pay_day.substring(interest_pay_day.length()-2, interest_pay_day.length());
		}
		return null;
	}

	public Map<String, String> readResFile(List<String> list) throws Exception {
        int res_f = 0;
        int res_s = 0;
        Map<String, String> result = new HashMap<>();
        List<String> errData = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
        	String str = list.get(i);
            String rspCode = DjsStringUtil.cutByGBK(str, 271, 2);
            if (rspCode.equals("00")) {
                String projectName = DjsStringUtil.trimFill(DjsStringUtil.cutByGBK(str, 50, 60),false);
                String borrAccountId = DjsStringUtil.cutByGBK(str, 110, 19);
                String loanAmt = DjsStringUtil.cutByGBK(str, 189, 13);
                String loanMent = DjsStringUtil.cutByGBK(str, 202, 4);
                String projectNo = DjsStringUtil.cutByGBK(str, 10, 40);
                //updateProjectMessage(projectName, borrAccountId, loanAmt, loanMent, projectNo);
                res_s++;
            } else {
                res_f++;
                String[] arry1 = {"15","16","17"};
                List<String> codeList = Arrays.asList(arry1);
                if (codeList.contains(rspCode)){
                    rspCode = "15";
                }
                errData.add(new StringBuffer("失败原因：").append(RespErrorCode.getName("BIDINRES" + rspCode)).append("，原数据为=========>").append(str).toString());
            }

            System.out.println(i+"/"+ list.size());
        }
        if (errData.size() > 0) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            result = ErrorFileUtil.handle(errData, "APPZXErrorDataFile" + simpleDateFormat.format(new Date()) + "00" + res_f + res_s);
        }
        System.out.println("失败F条数"+ res_f + "");
        System.out.println("成功S条数"+ res_s + "");
        System.out.println("处理总数"+ list.size()  + "");
        result.put("失败F条数", res_f + "");
        result.put("成功S条数", res_s + "");
        result.put("处理总数", list.size() + "");
        return result;
    }

    private void updateProjectMessage(String projectName, String borrAccountId, String loanAmt, String loanMent, String projectNo) {
        String sql = "Update jx_invest_project set PROJECT_NAME = ?, BORROWER_ACCOUNT_ID = ?,LOAN_AMT = ?, LOAN_MENT = ? where PROJECT_NO = ?";
        jdbcTemplate.update(sql, projectName, borrAccountId, loanAmt, loanMent, projectNo);
    }

}